import {defineStore} from "pinia";
import {getOrderByUserId} from "@/router/api";

interface OrderData {
    id: number
    no: string
    total: number,
    pay_type: number
}

export const useOrderStore = defineStore('order', {
    state: () => ({
        currentOrder: null as OrderData | null,
        orderHistory: [] as OrderData[],
        // 新增临时立即购买订单项
        tempOrderItems: [] as any[] // 存储立即购买的商品
    }),
    getters: {
        // 新增安全访问方法
        safeCurrentOrder: (state) => {
            if (!state.currentOrder) {
                throw new Error('当前订单未初始化')
            }
            return state.currentOrder
        },
        // 计算立即购买商品总价
        tempOrderTotal: (state) => {
            return state.tempOrderItems.reduce((total, item) => {
                return total + item.sale_price * item.num;
            }, 0).toFixed(2);
        },
    },
    actions: {
        setCurrentOrder(order: OrderData) {
            this.currentOrder = order
            this.orderHistory.unshift(order) // 添加到历史记录
        },

        // 设置立即购买的商品
        setTempOrderItems(product: any, quantity: number, goodid: number) {
            this.tempOrderItems = [{...product, num: quantity, goodid: goodid}]
        },
        // 清空临时订单
        clearTempOrder() {
            this.tempOrderItems = []
        },

        // 从API加载历史订单
        async loadOrderHistory(userId: number) {
            const res = await getOrderByUserId(userId)
            this.orderHistory = res.data
        },
    }
})